<?php
    class WZ_Event 
    {
        private static $_events = array();

        public static function reset() 
        {
            static::$_events = array();
        }

        public static function set($name, $function, $arguments = array(), $priority = null) 
        {
            if (!isset(static::$_events[$name])) {
                static::$_events[$name] = array();
            }

            if (!isset(static::$_events[$name][$priority])) {
                static::$_events[$name][$priority] = array();
            }

            static::$_events[$name][$priority][] = array(
                "function" => $function,
                "arguments" => $arguments
            );

            ksort(static::$_events[$name]);
        }

        public static function delete($name, $function = null) 
        {
            if(!isset(static::$_events[$name]))
                return;

            if($function === null) {
                unset(static::$_events[$name]);
                return;
            }

            foreach (static::$_events[$name] as $k => $priority_events) {
                foreach($priority_events as $ik => $item) {
                    if($item['function'] == $function) {
                        unset(static::$_events[$name][$k][$ik]);
                    }
                }
            }

            if(empty(static::$_events[$name])) {
                unset(static::$_events[$name]);
            }
        }
        
        public static function has_events($name)
        {
            if (isset(static::$_events[$name]) && count(static::$_events[$name]) > 0) {
                return true;
            }
            return false;
        }

        public static function run($name, $arguments = array(), $halt = false) 
        {
            if(!isset(static::$_events[$name])) {
                return;
            }
            foreach (static::$_events[$name] as $priority_events) {
                foreach($priority_events as $item) {
                    $response = call_user_func_array($item["function"], array_merge($item["arguments"], $arguments));
                    if (true === $halt && !is_null($response)) {
						return $response;
					}
                }
                $responses[] = $response;
            }

            return (true === $halt) ? null : $responses;
        }
        
        public static function shutdown()
        {
            if (static::has_events('shutdown')) {
                static::run('shutdown');
            }
	}
    }